package engineer.producers;

import design_patterns.command.Command;
import engineer.TypeMapper;
import entity_model.Attribute;
import entity_model.Entity;
import mysql.ColumnDefinition;
import mysql.Connection;
import mysql.Schema;
import mysql.types.Type;
import mysql.types.Types;

import static entity_model.Relationship.Role.Cardinality.MANY;
import static mysql.types.Types.INT;
import static mysql.types.Types.TIMESTAMP;

/**
 * Created by nuno-rafael-figueiredo on 02-07-2014.
 */
public class CreateTable extends Command {
    private static final ColumnDefinition ID = new ColumnDefinition("id", INT).primary(true);

    private static final ColumnDefinition CREATED_AT = new ColumnDefinition("created_at", TIMESTAMP);
    private static final ColumnDefinition UPDATED_AT = new ColumnDefinition("updated_at", TIMESTAMP);
    private static final ColumnDefinition DELETED_AT = new ColumnDefinition("deleted_at", TIMESTAMP);

    private Entity entity;

    public CreateTable(Entity entity){
        this.entity = entity;
    }

    @Override
    public void execute() {
        Schema schema = new Connection("localhost", "root", "root", "agendamento").extract();

        mysql.ddl.CreateTable createTable = new mysql.ddl.CreateTable(schema, entity.getTitle().getSingularized().toSnakeCase(), ID);

        bind(createTable);

        entity.getRelateds().stream().filter(related -> related.getMyRoleCardinality() == MANY).forEach(related -> createTable.createColumn(related.getTheOthersRoleTitle().getSingularized().suffix("_id").toSnakeCase(), Types.INT));

        for (Attribute attribute : entity.getAttributes())
            createTable.add(createColumnDefinition(attribute));

        createTable.add(CREATED_AT, UPDATED_AT, DELETED_AT);

        createTable.execute();
    }

    private ColumnDefinition createColumnDefinition(Attribute attribute) {
        String name = attribute.getTitle().toSnakeCase();

        Type type = TypeMapper.toMySQL(attribute.getDataType());

        return new ColumnDefinition(name, type);
    }
}
